package com.daocao.hua.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daocao.hua.R;
import com.daocao.hua.constant.Const;
import com.daocao.hua.util.EasyPermissions;
import com.daocao.hua.view.LoadingDialog;
import com.daocao.hua.view.V19FrameLayout;
import com.githang.statusbar.StatusBarCompat;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

/**
 * Created by Administrator on 2017/5/9.
 * 立木基类，继承了权限，和RX的生命周期
 */

public class BaseLiMuActivity extends kangcheng.com.lmzx_android_sdk_v10.ui.BaseActivity implements EasyPermissions.PermissionCallbacks, LifecycleProvider<ActivityEvent> {
    private boolean statusBar;
    private TextView mTitle, mLeftTextBtn, mRightTextBtn;
    private ImageButton  mRightImgBtn;
    private ImageView mLeftImgBtn;
    private LinearLayout mContent, mStatusBar, mBaseView;
    private V19FrameLayout mTitleBar;
    private Context context;
    private String activityName;
    private int viewType = 0;
    protected static final int RC_PERM = 123;

    protected int reSting = R.string.ask_again;//默认提示语句

    protected LoadingDialog mLoadingDialog;


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#FFFFFF"));
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        lifecycleSubject.onNext(ActivityEvent.CREATE);


        mLoadingDialog = new LoadingDialog(this);

        // 友盟统计
//        AnalyticsConfig.setAppkey(this, "583be97d677baa7c71000b1d");
//        MobclickAgent.setDebugMode(true);
//        MobclickAgent.updateOnlineConfig(this);
    }

    public void setBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().setNavigationBarColor(BaseActivity.this.getResources().getColor(R.color.black));
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setNavigationBarTintColor(Color.parseColor("#000000"));
            tintManager.setStatusBarTintEnabled(true);
//            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#e3483d"));
        }
    }


    // 初始化
    public void baseInitView(Context context, String activityName, int viewType) {
        this.context = context;
        this.activityName = activityName;
        this.viewType = viewType;

        mBaseView = (LinearLayout) findViewById(R.id.ll_base_view);
        mTitleBar = (V19FrameLayout) findViewById(R.id.titlebar);
        mTitle = (TextView) findViewById(R.id.title_text);
        mLeftTextBtn = (TextView) findViewById(R.id.left_text);
        mLeftImgBtn = (ImageView) findViewById(R.id.left_img);
        mRightTextBtn = (TextView) findViewById(R.id.right_text);
        mRightImgBtn = (ImageButton) findViewById(R.id.right_img);

    }


    // 设置要显示的布局方法
    public void setBaseContentView(int layoutId) {
        setContentView(R.layout.base_activity);
        mContent = (LinearLayout) findViewById(R.id.content);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(layoutId, null);
        mContent.addView(view);
    }

    // 设置要显示的布局方法
    public void setSecContentView(int layoutId) {
        setContentView(R.layout.base_sec_activity);
        initSecBar();
        mContent = (LinearLayout) findViewById(R.id.content);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(layoutId, null);
        mContent.addView(view);
    }

    public void initSecBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setNavigationBarTintColor(Color.parseColor("#000000"));
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setNavigationBarTintEnabled(true);
        }
//        com.githang.statusbar.StatusBarCompat.setStatusBarColor(this, Color.parseColor("#e3483d"));
    }

    public void setBaseBackground(int color) {
        mContent.setBackgroundColor(color);
    }

    public LinearLayout getBaseView() {
        return mBaseView;
    }

    public LinearLayout getStatusBar() {
        return mStatusBar;
    }

    public V19FrameLayout getTitleBar() {
        return mTitleBar;
    }

    public TextView getTitleText() {
        return mTitle;
    }

    public void isToolbarVisibilty(boolean f) {
        if (f) {
            mTitleBar.setVisibility(View.GONE);
        } else {
            mTitleBar.setVisibility(View.VISIBLE);
        }
    }

    public void setTitleText(String text) {
        mTitle.setText(text);
    }

    public TextView getLeftTextBtn() {
        return mLeftTextBtn;
    }

    public void setLeftTextBtn(String text) {
        mLeftTextBtn.setText(text);
    }

    public TextView getRightTextBtn() {
        return mRightTextBtn;
    }

    public void setRightTextBtn(String text) {
        mRightTextBtn.setText(text);
    }

    public ImageView getLeftImgBtn() {
        return mLeftImgBtn;
    }

    public void setLeftImgBtn(int resId) {
        mLeftImgBtn.setImageResource(resId);
    }

    public ImageButton getRightImgBtn() {
        return mRightImgBtn;
    }

    public void setRightImgBtn(int resId) {
        mRightImgBtn.setImageResource(resId);
    }

    //返回上一个Activity
    public void setBackIntent() {
        mLeftImgBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    // 跳转下一个Activity
    public void startNextIntent(final Context context, final Class<?> toClass) {
        mRightTextBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, toClass));
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.left_enter, R.anim.right_out);
    }


    @Override
    protected void onResume() {
        super.onResume();
//        JPushInterface.onResume(context);
        lifecycleSubject.onNext(ActivityEvent.RESUME);
        if (viewType == Const.ViewType.ACTIVITY)
            MobclickAgent.onPageStart(activityName);
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
//        JPushInterface.onPause(context);
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        if (viewType == Const.ViewType.ACTIVITY)
            MobclickAgent.onPageEnd(activityName);
        MobclickAgent.onPause(this);
    }


    @Override
    @CallSuper
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
    }


    @Override
    @CallSuper
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        super.onDestroy();
    }


    /**
     * 权限回调接口
     */
    private BaseLiMuActivity.CheckPermListener mListener;


    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();


    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }

    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }


    public interface CheckPermListener {
        //权限通过后的回调方法
        void superPermission();
    }

    public void checkPermission(BaseLiMuActivity.CheckPermListener listener, int resString, int reSting, String... mPerms) {
        this.reSting = reSting;
        mListener = listener;
        if (EasyPermissions.hasPermissions(this, mPerms)) {
            if (mListener != null)
                mListener.superPermission();
        } else {
            EasyPermissions.requestPermissions(this, getString(resString),
                    RC_PERM, mPerms);
        }
    }

    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //同意了某些权限可能不是全部
    }

    @Override
    public void onPermissionsAllGranted() {
        if (mListener != null)
            mListener.superPermission();//同意了全部权限的回调
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
                getString(R.string.perm_tip1) + getString(reSting) + getString(R.string.perm_tip2),
                R.string.setting, R.string.cancel, null, perms);
    }

}
